package com.mes.cloud.service;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mes.cloud.api.dto.request.SubordinateRequest;
import com.mes.cloud.api.dto.request.position.BatchDeletePositionSuperiorRequest;
import com.mes.cloud.api.dto.request.position.BindPositionSuperiorRequest;
import com.mes.cloud.api.dto.request.position.SysPositionSuperiorPageRequest;
import com.mes.cloud.api.dto.request.position.SysPositionSuperiorRequest;
import com.mes.cloud.api.dto.response.position.SysPositionSuperiorDto;
import com.mes.cloud.exception.BaseException;
import com.mes.cloud.common.CommPager;
import com.mes.cloud.common.JsonResult;
import com.mes.cloud.constant.Constants;
import com.mes.cloud.dao.SysPositionSuperiorDao;
import com.mes.cloud.entity.SysPositionLog;
import com.mes.cloud.entity.SysPositionSuperior;
import com.mes.cloud.entity.vo.position.SysPositionSuperiorVo;
import com.mes.cloud.enums.HttpStatusEnum;
import com.mes.cloud.util.DateUtil;
import com.mes.cloud.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 岗位上级岗位关联表
 *
 * @author 郑样平
 * @version 2019-08-26 14:29:01
 * @email xiaomin.wu1@pactera.com
 */
@Service
public class SysPositionSuperiorService {

    private SysPositionSuperiorDao sysPositionSuperiorDao;

    private IPKeyGenerator iPKeyGenerator;

    private LogService logService;

    @Autowired
    public SysPositionSuperiorService(SysPositionSuperiorDao sysPositionSuperiorDao, IPKeyGenerator iPKeyGenerator, LogService logService) {
        this.sysPositionSuperiorDao = sysPositionSuperiorDao;
        this.iPKeyGenerator = iPKeyGenerator;
        this.logService = logService;
    }

    /**
     * 上级岗位列表
     *
     * @param pageRequest
     * @return JsonResult
     */
    public JsonResult<CommPager<SysPositionSuperiorDto>> positionSuperiorList(SysPositionSuperiorPageRequest pageRequest) {
        Page<SysPositionSuperiorDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        //查询条件
        List<SysPositionSuperiorVo> sysPositionSuperiorVos = sysPositionSuperiorDao.positionSuperiorList(pageRequest);
        List<SysPositionSuperiorDto> sysPositionSuperiorDtoList = new ArrayList<>();
        for (SysPositionSuperiorVo sysPositionSuperiorVo : sysPositionSuperiorVos) {
            SysPositionSuperiorDto sysPositionSuperiorDto = new SysPositionSuperiorDto();
            BeanUtils.copyProperties(sysPositionSuperiorVo, sysPositionSuperiorDto);
            sysPositionSuperiorDtoList.add(sysPositionSuperiorDto);
        }
        CommPager<SysPositionSuperiorDto> pageResult = new CommPager<>(page, sysPositionSuperiorDtoList);
        JsonResult<CommPager<SysPositionSuperiorDto>> jsonResult = new JsonResult<>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);
        return jsonResult;
    }

    /**
     * 描述 移除上级岗位
     *
     * @param batchDeleteRequest
     * @return com.shinho.tntframe.core.common.model.JsonResult
     * @author 郑样平
     * @date 2019/8/26 15:41
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult batchDeletePositionSuperior(BatchDeletePositionSuperiorRequest batchDeleteRequest) {
        JsonResult jsonResult = new JsonResult();
        int count = sysPositionSuperiorDao.batchDelete(batchDeleteRequest.getIds());
        if (count > 0) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
            this.insertLog(batchDeleteRequest.getPositionId(), Constants.REMOVE_SUPERIOR_POSITION);
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(), HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * 描述 绑定上级岗位
     *
     * @param bindPositionSuperiorRequest
     * @return com.shinho.tntframe.core.common.model.JsonResult
     * @author 郑样平
     * @date 2019/8/26 15:41
     */
    public JsonResult bindPositionSuperior(BindPositionSuperiorRequest bindPositionSuperiorRequest) {
        JsonResult jsonResult = new JsonResult();
        //获取员工已有岗位
        SysPositionSuperior sysPositionSuperior = new SysPositionSuperior();
        sysPositionSuperior.setPositionId(bindPositionSuperiorRequest.getPositionId());
        //未删除状态
        sysPositionSuperior.setDelFlag(Constants.DEL_FLAG_NO);
        List<SysPositionSuperior> sysPositionSuperiorList = sysPositionSuperiorDao.select(sysPositionSuperior);
        if (sysPositionSuperiorList.size() > 0) {
            return jsonResult.setCode(HttpStatusEnum.REF_EXIST_POSITION_SUPERIOR.getCode()).setMsg(HttpStatusEnum.REF_EXIST_POSITION_SUPERIOR.getMessage());
        }
        //新增角色剔除已有岗位
        Set<String> idList = deleteExistPositionId(sysPositionSuperiorList, bindPositionSuperiorRequest.getIds());

        //组装岗位对象
        List<SysPositionSuperior> sysPositionSuperiors = generatorSysPositionSuperior(idList, bindPositionSuperiorRequest.getPositionId());
        if (CollectionUtils.isEmpty(sysPositionSuperiors)) {
            return jsonResult.setCode(HttpStatusEnum.REF_NO_POSITION_SUPERIOR.getCode()).setMsg(HttpStatusEnum.REF_NO_POSITION_SUPERIOR.getMessage());
        }
        //不能把子下级岗位设为上级岗位
        for (SysPositionSuperior sysPositionSuperior1 : sysPositionSuperiors) {
            SysPositionSuperior sysPositionSuperior2 = new SysPositionSuperior();
            sysPositionSuperior2.setPositionSuperiorId(bindPositionSuperiorRequest.getPositionId());
            sysPositionSuperior2.setPositionId(sysPositionSuperior1.getPositionSuperiorId());
            //未删除状态
            sysPositionSuperior2.setDelFlag(Constants.DEL_FLAG_NO);
            List<SysPositionSuperior> sysPositionSuperiorList2 = sysPositionSuperiorDao.select(sysPositionSuperior2);
            //不能关联下级为上级岗位
            if (sysPositionSuperiorList2.size() > 0) {
                return jsonResult.setCode(HttpStatusEnum.REF_NO_POSITION_LOWER.getCode()).setMsg(HttpStatusEnum.REF_NO_POSITION_LOWER.getMessage());
            }
        }
        //批量插入
        int count = sysPositionSuperiorDao.batchInsert(sysPositionSuperiors);
        if (count > 0) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
            this.insertLog(bindPositionSuperiorRequest.getPositionId(), Constants.ADD_SUPERIOR_POSITION);
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(), HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * 描述  剔除以及存在的岗位
     *
     * @param sysPositionSuperiorList, idList]
     * @return java.util.Set<java.lang.String>
     * @author 郑样平
     * @date 2019/8/26 17:26
     */
    private Set<String> deleteExistPositionId(List<SysPositionSuperior> sysPositionSuperiorList, Set<String> idList) {
        if (CollectionUtils.isEmpty(sysPositionSuperiorList)) {
            return idList;
        }
        List<String> existIdList = new ArrayList<>();
        //员工已经拥有的岗位ID存放到existIdList
        for (SysPositionSuperior sysPositionSuperior : sysPositionSuperiorList) {
            existIdList.add(sysPositionSuperior.getPositionId());
        }
        return deleteExistId(existIdList, idList);
    }

    /**
     * 描述 剔除以及存在的岗位
     *
     * @param existIdList, idList]
     * @return java.util.Set<java.lang.String>
     * @author 郑样平
     * @date 2019/8/26 17:27
     */
    private Set<String> deleteExistId(List<String> existIdList, Set<String> idList) {
        Set<String> returnList = new HashSet<>();
        for (String id : idList) {
            //判断id是否存在existIdList列表中
            if (!existIdList.contains(id)) {
                returnList.add(id);
            }
        }
        return returnList;
    }

    /**
     * 描述 组装岗位对象
     *
     * @param positionId, id
     * @return com.shinho.crm.base.entity.SysPositionSuperior
     * @author 郑样平
     * @date 2019/8/26 17:25
     */
    private List<SysPositionSuperior> generatorSysPositionSuperior(Set<String> idList, String positionId) {
        List<SysPositionSuperior> sysPositionSuperiors = new ArrayList<SysPositionSuperior>();
        if (CollectionUtils.isEmpty(idList)) {
            return sysPositionSuperiors;
        }
        SysPositionSuperior sysPositionSuperior = null;
        for (String id : idList) {
            //自己不能关联自己
            if (positionId.equals(id)) {
                continue;
            }
            sysPositionSuperior = generatorSysEmployeeRole(positionId, id);
            sysPositionSuperiors.add(sysPositionSuperior);
        }
        return sysPositionSuperiors;
    }

    /**
     * 描述 组装岗位对象
     *
     * @param positionId, id
     * @return com.shinho.crm.base.entity.SysPositionSuperior
     * @author 郑样平
     * @date 2019/8/26 17:25
     */
    private SysPositionSuperior generatorSysEmployeeRole(String positionId, String id) {
        SysPositionSuperior sysPositionSuperior = new SysPositionSuperior();
        sysPositionSuperior.setId(iPKeyGenerator.getGenerateKey());
        sysPositionSuperior.setPositionId(positionId);
        sysPositionSuperior.setPositionSuperiorId(id);
        sysPositionSuperior.setUpdateDateStr(DateUtil.updateDateStr());
        sysPositionSuperior.setCreateBy(UserUtil.getCreateByName());
        sysPositionSuperior.setUpdateBy(UserUtil.getUpdateByName());
        sysPositionSuperior.setCreateByNo(UserUtil.getCreateByNo());
        sysPositionSuperior.setUpdateByNo(UserUtil.getUpdateByNo());
        return sysPositionSuperior;
    }

    /**
     * 描述  插入日志
     *
     * @param id, logMessage]
     * @return void
     * @author 郑样平
     * @date 2019/8/26 17:28
     */
    private void insertLog(String id, String logMessage) {
        SysPositionLog sysPositionLog = new SysPositionLog();
        sysPositionLog.setPositionId(id);
        sysPositionLog.setMenuCode(Constants.POSITION_MENU_CODE);
        sysPositionLog.setLog(logMessage);
        sysPositionLog.setId(iPKeyGenerator.getGenerateKey());
        sysPositionLog.setUpdateDateStr(DateUtil.updateDateStr());
        sysPositionLog.setCreateBy(UserUtil.getCreateByName());
        sysPositionLog.setUpdateBy(UserUtil.getUpdateByName());
        sysPositionLog.setCreateByNo(UserUtil.getCreateByNo());
        sysPositionLog.setUpdateByNo(UserUtil.getUpdateByNo());
        logService.insertPositionLog(sysPositionLog);
    }


    /**
     * 上级岗位列表
     *
     * @param request
     * @return JsonResult
     */
    public JsonResult<SysPositionSuperiorDto> getSysPositionSuperior(SysPositionSuperiorRequest request) {
        JsonResult<SysPositionSuperiorDto> jsonResult = new JsonResult<>();
        SysPositionSuperior sysPositionSuperior = new SysPositionSuperior();
        sysPositionSuperior.setPositionId(request.getPositionId());
        sysPositionSuperior.setDelFlag(Constants.DEL_FLAG_NO);
        sysPositionSuperior.setEnableFlag(Constants.ENABLE_FLAG_YES);
        sysPositionSuperior = sysPositionSuperiorDao.selectOne(sysPositionSuperior);
        if (Objects.isNull(sysPositionSuperior)) {
            return jsonResult.setCode(HttpStatusEnum.RECORD_NOT_EXIST.getCode()).setMsg(HttpStatusEnum.RECORD_NOT_EXIST.getMessage());
        }
        SysPositionSuperiorDto sysPositionSuperiorDto = new SysPositionSuperiorDto();
        BeanUtils.copyProperties(sysPositionSuperior, sysPositionSuperiorDto);
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(sysPositionSuperiorDto);
        return jsonResult;
    }

    /**
     * 描述 包含未停用的下级
     *
     * @param subordinateRequest
     * @return com.shinho.tntframe.core.common.model.JsonResult<java.lang.String>
     * @author 郑样平
     * @date 2019/12/9 16:48
     */
    public JsonResult<String> getSubordinate(SubordinateRequest subordinateRequest) {
        JsonResult jsonResult = new JsonResult();
        String flag = "0";
        if (!CollectionUtils.isEmpty(subordinateRequest.getPositionIds())) {
            for (String positionId : subordinateRequest.getPositionIds()) {
                SysPositionSuperior sysPositionSuperior = new SysPositionSuperior();
                sysPositionSuperior.setPositionSuperiorId(positionId);
                sysPositionSuperior.setDelFlag(Constants.DEL_FLAG_NO);
                int count = sysPositionSuperiorDao.selectCount(sysPositionSuperior);
                if (count > 0) {
                    flag = Constants.DEL_FLAG_YES;
                    break;
                }
            }
        }
        return jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(flag);
    }
}
